import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { Card, Input, Space, Button } from "antd";
import request from "../../utils/request";

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const history = useHistory();

  const onLoginClicked = async () => {
    console.log(username, password);
    // 请求登录
    const res = await request.post("/login", { username, password });
    console.log("res", res);
    // 如果登录成功，保存用户登录状态
    window.sessionStorage.setItem("token", res.data.token);
    window.sessionStorage.setItem("user", JSON.stringify(res.data.user));
    // 跳转路由
    history.push("/blogs");
  };

  return (
    <div className="login">
      <Card title="登录博客">
        <Space direction="vertical" style={{ width: "100%" }}>
          <Input
            placeholder="用户名"
            onChange={(e) => setUsername(e.target.value)}
          />

          <Input.Password
            placeholder="密码"
            onChange={(e) => setPassword(e.target.value)}
          />

          <Button type="ghost" onClick={onLoginClicked}>
            登录
          </Button>
        </Space>
      </Card>
    </div>
  );
};

export default Login;
